package com.atguigu.common.util;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
// @Accessors(chain = true)
@ApiModel("统一响应数据模型")
public class R implements Serializable {

    private static final long serialVersionUID = 101L;

    @ApiModelProperty("是否成功")
    private Boolean success;

    @ApiModelProperty("状态码")
    private Integer code;

    @ApiModelProperty("附加信息")
    private String message;

    @ApiModelProperty("返回数据")
    private Map<String, Object> data = new HashMap<>();

    // 私有化（相当于禁用）空构造函数
    private R() {
    }

    // 成功
    public static R ok() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(StatusCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }

    // 失败
    public static R error() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(StatusCode.ERROR);
        r.setMessage("失败");
        return r;
    }



    public R success(Boolean success) {
        this.setSuccess(success);
        return this;
    }

    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    public R message(String message) {
        this.setMessage(message);
        return this;
    }

    public R data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> data) {
        this.setData(data);
        return this;
    }

    public R dataTotal(Long total) {
        this.data.put("total", total);
        return this;
    }

    public R dataItems(List<?> list) {
        this.data.put("total", list.size());
        this.data.put("items", list);
        return this;
    }

    public R dataRows(List<?> list) {
        this.data.put("total", list.size());
        this.data.put("rows", list);
        return this;
    }
}
